package cn.wqk.rrtf.controller;

import cn.wqk.rrtf.pojo.User;
import cn.wqk.rrtf.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpSession session,
                        Model model){
        System.out.println(username);
        System.out.println(password);
        //获取当前登录用户
        Subject subject= SecurityUtils.getSubject();
        //封装用户登录的数据，以便校验
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        try {//成功
            subject.login(token);//subject对象匹配token里的登录密码
            User user = userService.selectUserByUsername(username);
            session.setAttribute("user",user);
            return "index";
        }catch (UnknownAccountException e){//用户名不存在
            model.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){//密码错误
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }
}
